<?php

class session
{
	
	public static function exist($sid, $ip)
	{
		global $db;
		
		$query = 'SELECT `id`, `sid`, `ip_address`, `date` FROM sessions WHERE `sid` = "' . $db->escape($sid) . '" AND `ip_address` = "' . $db->escape($ip) . '";';
		$result = $db->query($query);
		if ($result && $db->numrows($result) > 0)
		{
			$return = $db->frow($result);
			$db->free($result);
			return($return);
		}
		$db->free($result);
		return(false);
	}
	
	public static function create($id, $sid, $ip)
	{
		global $db;
		
		$exist = self::exist($sid, $ip);
		if (!$exist)
		{
			$time = time();
			$query = 'INSERT INTO sessions VALUES ("' . intval($id) . '", "' . $db->escape($sid) . '", "' . $db->escape($ip) . '", "' . intval($time) . '");';
			$result = $db->query($query);
			if ($result)
			{
				$_SESSION['sid'] = $sid;
				return(true);
			}
			return(false);
		}
		return('exist');
	}
	
	public static function renew($sid, $ip)
	{
		global $db;
		
		$exist = self::exist($sid, $ip);
		
		if ($exist)
		{
			$new_time = time();
			if (($exist['date'] + expire_time) > $new_time)
			{
				$upd_query = 'UPDATE sessions SET `date` = "' . intval($new_time) . '" WHERE `sid` = "' . $db->escape($sid) . '" AND `ip_address` = "' . $db->escape($ip) . '";';
				$result = $db->query($upd_query);
				if ($result)
				{
					return(true);
				}
				return(false);
			}
			self::delete($sid, $ip);
			return(false);
		}
		return('exist');		
	}
	
	public static function delete($sid, $ip)
	{
		global $db;
		
		$exist = self::exist($sid, $ip);
		if ($exist)
		{
			$del_query = 'DELETE FROM sessions WHERE `sid` = "' . $db->escape($sid) . '" AND `ip_address` = "' . $db->escape($ip) . '";';
			$result = $db->query($del_query);
			if ($result)
			{
				$_SESSION['sid'] = '';
				unset($_SESSION['sid']);
				return(true);
			}
			return(false);
		}
		return('exist');	
	}
	
	public static function clear_old()
	{
		global $db;
		
		// 20 Minutes.
		$expire_time = time() + expire_time;
		$del_query = 'DELETE FROM sessions WHERE `date` > "' . intval($expire_time) . '";';
		$result = $db->query($del_query);
		
		if ($result)
		{
			return(true);
		}
		return(false);
	}

}